<template>
  <div class="search">
    <!-- 公共头部 -->
    <CommonHeader>
      <template #left>
        <div>
          <Icon name="zuojiantou"></Icon>
          <span>返回</span>
        </div>
      </template>
      <template #title>
        <input
          class="search-input"
          v-focus
          type="text"
          v-model="searchInput"
          @keyup.enter="handleSearch"
          placeholder="请输入关键字"
        />
      </template>
      <template #right>
        <div @click="handleSearch">
          <Icon name="search" size="25px"></Icon>
        </div>
      </template>
    </CommonHeader>

    <!-- 历史记录：仅当存在历史时显示 -->
    <div class="search_history" v-if="searchHistory.length > 0">
      <div class="search_history_title">
        <div class="search_history">历史记录</div>
        <div class="search_history_clear" @click="clearSearchHistory">
          删除全部
        </div>
      </div>
      <div class="search_history_list">
        <div
          class="search_history_item"
          v-for="item in searchHistory"
          :key="item"
          @click="onHistoryClick(item)"
        >
          {{ item }}
        </div>
      </div>
    </div>

    <!-- 商品列表 or 空状态 -->
    <div class="productList_content">
      <!-- 搜索无结果 -->
      <div v-if="searchList.length === 0 && isSearchMode" class="no-result">
        <p>未匹配到相关商品</p>
      </div>

      <!-- 正常商品列表 -->
      <div class="list_item" v-for="item in searchList" :key="item.id">
        <div class="list_item_img">
          <!-- <img :src="item.img" alt="" /> -->
          <CustomImage :src="item.img" />
        </div>
        <div class="list_item_info">
          <div
            class="list_item_info_title"
            v-highlight="{
              keyword: searchInput,
              color: 'red',
              backgroundColor: 'yellow',
            }"
          >
            {{ item.goodsname }}
          </div>
          <div class="list_item_info_desc">
            {{ item.goodsdesc || '暂无描述' }}
          </div>
          <div class="list_item_info_price">
            <span>¥{{ item.price }}</span>
            <del class="market">¥{{ item.market_price }}</del>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import CommonHeader from '@/components/common/publicHeader/index.vue';

import { getGoodListAPI } from '@/api/home';
import { getSearchGoods } from '@/api/search';
import CustomImage from '@/components/common/Image/index.vue';

const SEARCH_HISTORY_KEY = 'searchHistory';

export default {
  components: {
    CommonHeader,
    CustomImage,
  },
  data() {
    return {
      searchInput: '',
      searchList: [],
      originalList: [], // 存储原始商品数据，用于清空搜索后恢复
      goodListParams: {
        cateid: this.$route.query.id,
        type: this.$route.query.type,
        page: 1,
        size: 6,
      },
      searchHistory: this.loadSearchHistory(),
      isSearchMode: false, // 标记当前是否处于搜索状态
    };
  },
  created() {
    this.getGoodList();
  },
  methods: {
    // 获取初始商品列表
    async getGoodList() {
      const res = await getGoodListAPI(this.goodListParams);
      const {
        list: { goodData },
      } = res;
      const formattedData = goodData.map(item => ({
        ...item,
        img: 'http://43.138.15.137:4000' + item.img,
      }));
      this.searchList = formattedData;
      this.originalList = formattedData; // 保存原始数据
    },

    // 处理搜索逻辑
    async handleSearch() {
      const keyword = this.searchInput.trim();

      // 如果输入为空，则恢复原始商品列表
      if (!keyword) {
        this.searchList = this.originalList;
        this.isSearchMode = false;
        return;
      }

      // 添加到搜索历史
      this.addToSearchHistory(keyword);

      try {
        const res = await getSearchGoods({ keywords: keyword });
        const { list } = res;

        if (Array.isArray(list) && list.length > 0) {
          this.searchList = list.map(item => ({
            ...item,
            img: 'http://43.138.15.137:4000' + item.img,
          }));
        } else {
          this.searchList = [];
        }
      } catch (error) {
        console.error('搜索请求失败:', error);
        this.searchList = [];
      }

      this.isSearchMode = true;
    },

    // 点击历史记录触发搜索
    onHistoryClick(keyword) {
      this.searchInput = keyword;
      this.handleSearch();
    },

    // 添加搜索词到历史（去重 + 限制数量）
    addToSearchHistory(keyword) {
      let history = this.loadSearchHistory();

      // 去重：移除已存在的项
      history = history.filter(item => item !== keyword);
      // 添加到最前面
      history.unshift(keyword);
      // 最多保留 5 条
      if (history.length > 5) {
        history = history.slice(0, 5);
      }

      this.searchHistory = history;
      localStorage.setItem(SEARCH_HISTORY_KEY, JSON.stringify(history));
    },

    // 加载本地历史
    loadSearchHistory() {
      const saved = localStorage.getItem(SEARCH_HISTORY_KEY);
      return saved ? JSON.parse(saved) : [];
    },

    // 清空所有历史
    clearSearchHistory() {
      this.searchHistory = [];
      localStorage.removeItem(SEARCH_HISTORY_KEY);
    },
  },
};
</script>

<style lang="scss" scoped>
.search {
  height: 100%;
  background-color: #eeeeee;

  .search_history {
    height: 100%;
    background-color: #fff;
    padding: 5px;

    .search_history_title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 16px;
      font-weight: 500;
      color: #333;

      .search_history {
        font-size: 16px;
        font-weight: 500;
        color: #333;
      }

      .search_history_clear {
        font-size: 14px;
        font-weight: 500;
        color: #999;
      }
    }

    .search_history_list {
      padding: 5px;
      margin-top: 10px;
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      gap: 10px;

      .search_history_item {
        font-size: 12px;
        font-weight: 500;
        color: #333;
        padding: 5px;
        border-radius: 5px;
        background-color: #eeeeee;
      }
    }
  }

  .productList_content {
    position: relative;
    margin-top: 0;
    padding: 8px 0;
    display: flex;
    flex-direction: column;
    gap: 8px;
    background-color: #fff;
    z-index: 1;

    .list_item {
      width: 100%;
      background-color: #fafafa;
      padding: 10px;
      display: flex;

      .list_item_img {
        width: 140px;
        height: 100px;
        margin-right: 10px;
      }

      .list_item_info {
        width: 100%;
        height: 100px;

        .list_item_info_title {
          font-size: 12px;
          font-weight: bold;
          // 最多显示2行
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }

        .list_item_info_desc {
          font-size: 14px;
          color: #999;
        }

        .list_item_info_price {
          font-size: 15px;
          margin: 20px 0;
          color: #ff6600;

          .market {
            color: #999;
            font-size: 12px;
            margin-left: 4px;
          }
        }
      }
    }
  }

  .no-result {
    text-align: center;
    color: #999;
    font-size: 14px;
    padding: 20px 0;
    background-color: #fff;
  }
}
</style>
